//index.js
var app = getApp();
var md5 = require("../../utils/MD5.js")
var checkNetWork = require("../../utils/CheckNetWork.js")
var disabledToken = require("../../utils/disabledToken.js")
//获取应用实例
Page({
  data: {
    //地图的宽高
    mapHeight: '100%',
    mapWidth: '100%',
    winHeigth: wx.getStorageSync("kScreenW") * 603,
    mapTop: '0',
    //正在骑行中的视图的属性
    bikeRiding: {
      show: false,
      ridingTime: 0,
      ridingDistance: 0,
      ridingSpeed: 0,
      height: '25%',
      width: '100%',
      topLineHeight: "0rpx",
      bottomLineHeight: "0rpx",
    },
    //是否能查询附近单车: 主要根据骑行中状态判断
    isCanGetBikeList: true,
    //用户当前位置
    point: {
      latitude: 0,
      longitude: 0
    },
    hasLoginMapControls: [
      {// //扫描二维码控件按钮
        id: 12,
        position: {
          left: 132.5 * wx.getStorageSync("kScreenW"),
          top: 523 * wx.getStorageSync("kScreenH"),
          width: 110 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/imgs_custom_scan@2x.png',
        clickable: true,
      },
      //隐藏说明按钮
      {
        position: {
          width: 1,
          height: 1
        },
        iconPath: '../../image/hidden_explain.png',
        clickable: false,
      },
      {
        id: 11,
        position: {
          left: 10 * wx.getStorageSync("kScreenW"),
          top: 123 * wx.getStorageSync("kScreenH"),
          width: 40 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/imgs_main_location@2x.png',
        clickable: true,
      },
      //钱包控件按钮
      {
        id: 13,
        position: {
          left: 330 * wx.getStorageSync("kScreenW"),
          top: 523 * wx.getStorageSync("kScreenH"),
          width: 40 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/imgs_menu_wallet@2x.png',
        clickable: true,
      },
      //地图中心位置按钮
      {
        id: 14,
        position: {
          left: 177.5 * wx.getStorageSync("kScreenW"),
          top: 105 * wx.getStorageSync("kScreenH"),
          width: 20 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/imgs_main_center@2x.png',
        clickable: false,
      }],
    //没有登录的地图组件
    notLoginMapControls: [
      {
        id: 16,
        position: {
          left: 132.5 * wx.getStorageSync("kScreenW"),
          top: 523 * wx.getStorageSync("kScreenH"),
          width: 110 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/login_register.png',
        clickable: true,
      },
      //显示说明按钮
      {
        id: 15,
        position: {
          left: 45 * wx.getStorageSync("kScreenW"),
          top: 20 * wx.getStorageSync("kScreenH"),
          width: 285 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/explain.png',
        clickable: true,
      },
      {
        id: 11,
        position: {
          left: 10 * wx.getStorageSync("kScreenW"),
          top: 523 * wx.getStorageSync("kScreenH"),
          width: 40 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/imgs_main_location@2x.png',
        clickable: true,
      },
      //钱包控件按钮
      {
        id: 13,
        position: {
          left: 330 * wx.getStorageSync("kScreenW"),
          top: 523 * wx.getStorageSync("kScreenH"),
          width: 40 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/imgs_menu_wallet@2x.png',
        clickable: true,
      },
      //地图中心位置按钮
      {
        id: 14,
        position: {
          left: 177.5 * wx.getStorageSync("kScreenW"),
          top: 261.5 * wx.getStorageSync("kScreenH"),
          width: 20 * wx.getStorageSync("kScreenW"),
          height: 40 * wx.getStorageSync("kScreenW")
        },
        iconPath: '../../image/imgs_main_center@2x.png',
        clickable: false,
      }],
    //检测骑行中的定时器是否已创建
    isCreateTimerStatu: false
  },

  //控件的点击事件
  controltap: function (e) {
    console.log(e)
    var that = this
    var id = e.controlId
    if (id == 11) {
      //定位当前位置
      that.getUserCurrentLocation()
    } else if (id == 12) {
      //扫描二维码 扫描二维码 扫描二维码 扫描二维码 扫描二维码 扫描二维码
      wx.scanCode({
        success: function (res) {
          // success
          var checksum = that.data.unlockBikeParams.token + res.result + that.data.SALT
          var checksumMd5 = md5.hexMD5(checksum)
          that.setData({
            'unlockBikeParams.device_id': res.result,
            'unlockBikeParams.checksum': checksumMd5
          })
          //扫码之后请求接口
          that.scanBikeQr()
        },
        fail: function () {
          // fail
          wx.showToast({
            title: '扫码失败',
            icon: 'loading',
            duration: 2000,
          })
        },
        complete: function () {
          // complete
        }
      })
    } else if (id == 13) {
      var token = wx.getStorageSync('token') || ''
      if (token.length > 0) {
        //进入钱包
        wx.navigateTo({
          url: '../wallet/wallet'
        })
      } else {
        //注册登录 
        wx.navigateTo({
          url: '../Register/Register'
        })
      }

    } else if (id == 15) {
      //使用说明
      wx.navigateTo({
        url: '../explain/explain'
      })
    } else if (id == 16) {
      //注册登录 
      wx.navigateTo({
        url: '../Register/Register'
      })
    }
  },


  //请求附近单车列表
  getBikeList: function () {
    //检查网络
    if (checkNetWork.checkNetWorkStatu() == false) {
      console.log('网络错误')
    } else {
      var that = this
      wx.request({
        url: that.data.AirBikeUrl.getlist,
        data: that.data.getBikeListParams,
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        // header: {}, // 设置请求的 header
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          // success
          var message = res.data.message
          var statu = res.data.status
          //检查是否登录失效
          disabledToken.reLogin(statu)
          wx.showToast({
            title: '查询附近单车:\n' + message,
            icon: 'success',
            duration: 2000,
          })
          var bikeArr = res.data.result
          var markers = []
          for (var i = 0; i < bikeArr.length; i++) {
            var bikeLat = Number(bikeArr[i].latitude)
            var bikeLong = Number(bikeArr[i].longitude)
            var id = Number(bikeArr[i].device_id)
            var marker = {
              latitude: bikeLat,
              longitude: bikeLong,
              iconPath: "../../image/imgs_main_bike@2x.png",
              id: id,
              width: 40 * wx.getStorageSync("kScreenW"),
              height: 40 * wx.getStorageSync("kScreenW")
            }
            markers.push(marker)
          }
          if (that.data.isCanGetBikeList) {
            that.setData({
              'markers': markers
            })
          }
          console.log(that.data.markers)
        },
        fail: function () {
          // fail
          that.failMessage()
        },
        complete: function () {
          // complete
          console.log("请求complete啊")
          setTimeout(function () {
            wx.hideToast()
          }, 1000)
        }
      })
    }
  },

  //位置变化的时候,包括范围变化，比如比例变大变小
  regionchange: function (e) {
    //得到地图中心点的位置
    wx.showToast({
      title: 'sssss',
    })
    var that = this
    that.mapCtx.getCenterLocation({
      success: function (res) {
        //调试发现地图在滑动屏幕开始和结束的时候都会走这个方法,需要判断位置是否真的变化来判断是否刷新单车列表
        //经纬度保留6位小数
        var longitudeFix = res.longitude.toFixed(6)
        var latitudeFix = res.latitude.toFixed(6)
        if (e.type == "begin") {
          console.log('位置相同,不执行刷新操作')
        } else {
          console.log("位置变化了")
          var checksum = that.data.getBikeListParams.token + longitudeFix + latitudeFix + that.data.SALT
          var checksumMd5 = md5.hexMD5(checksum)
          that.setData({
            'getBikeListParams.longitude': longitudeFix,
            'getBikeListParams.latitude': latitudeFix,
            'getBikeListParams.checksum': checksumMd5
          })
          //刷新单车列表
          if (that.data.isCanGetBikeList) {
            that.getBikeList()
          }
        }
      }
    })
  },

  //点击标注点
  markertap: function (e) {
    console.log(e.markerId)
  },

  //定位到用户当前位置
  getUserCurrentLocation: function () {
    this.mapCtx.moveToLocation();
    this.setData({
      'mapScale': 16
    })
  },

  failMessage: function () {
    wx.showToast({
      title: '连接服务器失败',
      icon: 'loading',
      duration: 2000,
    })
  },


  //页面加载的函数
  onLoad: function () {
    // 页面加载判断openid
    app.getUserInfo();
    // console.log("onload");

    var that = this;
    //获取用户的当前位置位置
    wx.getLocation({
      type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用wx.openLocation 的坐标
      success: function (res) {
        // success
        var latitude = res.latitude
        var longitude = res.longitude
        var point = {
          latitude: latitude,
          longitude: longitude
        };
        that.setData({
          'point': point
        })
      }
    })

    //查询商家列表
    getShoppingInfo(this);


    wx.getSystemInfo({//获取滑块的高宽
      success: function (res) {
        //console.log(res)
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
        });
      }
    });
    //如果APP被微信强制关闭或异常杀死,重启的情况下,检查用户的用车状态
    //如果未登录,则不做处理,否则请求查询接口
    var token = wx.getStorageSync('token') || ''
    if (checkNetWork.checkNetWorkStatu() == false) {
      console.log('网络错误')
    } else {
      if (token.length > 0) {
        //这一步是为了让onShow函数必须启动定时器到当前网络请求结束
        that.setData({
          "completeStatu": false
        })
        wx.request({
          url: that.data.AirBikeUrl.queryridingstatusUrl,
          data: {
            token: token,
            checksum: md5.hexMD5(token + that.data.SALT)
          },
          method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          // header: {}, // 设置请求的 header
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            // success
            console.log(res.data)
            var query_statu = res.data.status
            if (query_statu == 1) {
              //查询成功
              var result = res.data.result
              if (result.riding_status == 0) {
                //未骑行,未预约状态,什么也不做
              } else if (result.riding_status == 1) {
                //修改全局骑行状态为1
                getApp().globalData.isRidingBike = 1
                console.info("onload函数下的骑行状态参数")
                console.info(getApp().globalData.isRidingBike)
                //骑行状态,显示骑行视图
                var serial_no = result.riding_info.serial_no
                var lock_id = result.riding_info.lock_id
                //服务器返回开锁成功
                var checksum = token + lock_id + serial_no + that.data.SALT
                var checksumMd5 = md5.hexMD5(checksum)
                //将骑行中的接口参数赋值
                that.setData({
                  "ridingBikeParams.token": token,
                  "ridingBikeParams.device_id": lock_id,
                  "ridingBikeParams.serial_no": serial_no,
                  "ridingBikeParams.checksum": checksumMd5
                })
              } else if (result.riding_status == 2) {
                //预约状态,提示用户再APP上预约过单车
                wx.showModal({
                  title: '提示',
                  content: '系统检测到您已在APP端预约过单车,如果继续使用小程序扫码开锁,将会自动帮您取消掉预约状态',
                  showCancel: false,
                })
              }
            } else {
              //非法操作
              wx.showToast({
                title: '更新用户状态失败',
                icon: 'loading',
                duration: 2000,
              })
            }
          },
          fail: function () {
            // fail
          },
          complete: function () {
            // complete
            console.log("complete")
            that.setData({
              "completeStatu": true
            })
          }
        })
      }
    }
  },

  onReady: function (e) {
    //通过id获取map,然后创建上下文
    this.mapCtx = wx.createMapContext("myMap");
  },

  onShow: function () {
    // 生命周期函数--监听页面显示
    var that = this
    that.setData({
      'controls': that.data.hasLoginMapControls,
    })
  },
  onShareAppMessage: function () {
    // 用户点击右上角分享
    console.log('onShareAppMessage')
    return {
      desc: '我要喝酒', // 分享描述
      path: '/index/index' // 分享路径
    }
  }
  , searchs: function (e) {

  }
  , inputSearch: function (e) {
    if (e.detail.value != '') {
      this.setData({
        inputSearchs: e.detail.value
      })
    } else {
      this.setData({
        inputSearchs: ''
      })
    }
  },
  gotoShop: function (e) {
    var superID = e.currentTarget.dataset.id;
    // console.log(e.currentTarget.dataset.id);  
    wx.navigateTo({
      url: '../selectShopProduct/selectShopProduct?superID=' + superID,
    })
  }
})

function getShoppingInfo(that) {
  wx.request({
    url: app.globalData.allUrl + "/superMarketAction/skipPrefecture",
    data: {
      lon: 104.093900,
      lat: 30.661110
    },
    method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    // header: {}, // 设置请求的 header
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: function (reRes) {
      console.log(reRes.data);
      var markers = [];
      for (var i = 0; i < reRes.data.length; i++) {
        var oneMark = {
          iconPath: "../../image/dizhidw2x.png",
          id: i,
          latitude: reRes.data[i].latitude,
          longitude: reRes.data[i].longitude,
          width: 50,
          height: 50,         
        }
        markers.push(oneMark); 
      }
      that.setData({
        shoppingInfoList: reRes.data,
        markers: markers
      })
      //console.log(that.data.shoppingInfoList);
    },
    fail: function () {
      // fail
    },
  });
}